package com.youpai.platform.vulture.service.support;

import com.youpai.platform.vulture.service.channel.VultureChannel;
import com.youpai.platform.vulture.service.constant.BizConstants;
import com.youpai.platform.vulture.service.handler.detection.HeartbeatCheckHandler;
import com.youpai.platform.vulture.service.handler.detection.UnHandSharkConnectionCleanHandler;
import com.youpai.platform.vulture.service.handler.flag.HeartbeatMessageHandler;
import io.netty.util.HashedWheelTimer;
import java.util.concurrent.TimeUnit;

/**
 * @date: 2023/2/24 13:21
 * @author: Welles
 * @version: 1.0
 */
public class DetectionSupport {

    // 时间轮对象
    private static final HashedWheelTimer HASHED_WHEEL_TIMER = new io.netty.util.HashedWheelTimer(
            ThreadFactorySupport.getAnyModelThreadFactory(), 100,
            TimeUnit.MILLISECONDS, 512, true,
            -1);

    /**
     * 获取时间轮对象
     *
     * @return 时间轮对象
     */
    public static HashedWheelTimer getHashedWheelTimer() {
        return DetectionSupport.HASHED_WHEEL_TIMER;
    }

    /**
     * 开启心跳
     *
     * @param vultureChannel vultureChannel
     */
    public static void startHeartbeat(VultureChannel vultureChannel) {
        HeartbeatCheckHandler heartbeatCheckHandler = new HeartbeatCheckHandler(vultureChannel);
        HASHED_WHEEL_TIMER.newTimeout(heartbeatCheckHandler, BizConstants.HEARTBEAT_INTERVAL, TimeUnit.MILLISECONDS);
    }

    /**
     * 清除未握手连接
     *
     * @param vultureChannel vultureChannel
     */
    public static void cleanUnHandSharkConnection(VultureChannel vultureChannel) {
        // 创建未握手连接处理类
        UnHandSharkConnectionCleanHandler unHandSharkConnectionCleanHandler = new UnHandSharkConnectionCleanHandler(vultureChannel);
        HASHED_WHEEL_TIMER.newTimeout(unHandSharkConnectionCleanHandler, BizConstants.UN_HAND_SHARK_CONNECTION_TIME_OUT, TimeUnit.MILLISECONDS);
    }
}
